/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml;

import dto.Application;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import util.DateUtil;

/**
 *
 * @author phat10130059
 */
public class XmlFile {
    
    public static List<Application> readFileXml(String file) {
        List<Application> list = new ArrayList<Application>();
        
        try {
            
            File fXmlFile = new File(file);
            
            if (fXmlFile.exists() && !fXmlFile.isDirectory()) {
                
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);

                //optional, but recommended
                //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
                doc.getDocumentElement().normalize();
                
                System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
                
                NodeList nList = doc.getElementsByTagName("App");
                
                for (int temp = 0; temp < nList.getLength(); temp++) {
                    
                    Node nNode = nList.item(temp);

//                System.out.println("\nCurrent Element :" + nNode.getNodeName());

                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        
                        Application application = new Application();
                        
                        Element eElement = (Element) nNode;
                        
                        application.setId(eElement.getAttribute("id"));
                        application.setWindow(eElement.getElementsByTagName("window").item(0).getTextContent());
                        application.setUser(eElement.getElementsByTagName("user").item(0).getTextContent());
                        application.setStart(eElement.getElementsByTagName("start").item(0).getTextContent());
                        application.setEnd(eElement.getElementsByTagName("end").item(0).getTextContent());
                        application.setType(eElement.getElementsByTagName("type").item(0).getTextContent());
                        
                        
                        list.add(application);
                        
                        
                    }
                }
                
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return list;
    }
    
    public static void createXmlNew(String filePath, Application application) {
        try {

//            Date d1 = new Date();
//            SimpleDateFormat simpDate = new SimpleDateFormat("yyyyMMddHHmmss");
//            String id = simpDate.format(d1);

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("Computer");
            doc.appendChild(rootElement);

            // staff elements
            Element app = doc.createElement("App");
            rootElement.appendChild(app);

            // set attribute to staff element
            Attr attr = doc.createAttribute("id");
            attr.setValue(DateUtil.getDateTimeToString());
            app.setAttributeNode(attr);

            // shorten way
            // staff.setAttribute("id", "1");

            // firstname elements
            Element window = doc.createElement("window");
            window.appendChild(doc.createTextNode(application.getWindow()));
            app.appendChild(window);

            // lastname elements
            Element user = doc.createElement("user");
            user.appendChild(doc.createTextNode(application.getUser()));
            app.appendChild(user);

            // nickname elements
            Element start = doc.createElement("start");
            start.appendChild(doc.createTextNode(application.getStart()));
            app.appendChild(start);

            // salary elements
            Element end = doc.createElement("end");
            end.appendChild(doc.createTextNode(application.getEnd()));
            app.appendChild(end);

            // type elements
            Element type = doc.createElement("type");
            type.appendChild(doc.createTextNode(application.getType()));
            app.appendChild(type);


            // write the content into xml filePath
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));

            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

            transformer.transform(source, result);
            
            System.out.println("File saved!");
            
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }
    
    public static void createXmlExist(String filePath, Application application) {
        try {
            
            File fXmlFile = new File(filePath);
            
            if (fXmlFile.exists() && !fXmlFile.isDirectory()) {
                
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);

                //optional, but recommended
                //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
                doc.getDocumentElement().normalize();
                
                System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
                
                Element rootElement = doc.getDocumentElement();

                // staff elements
                Element app = doc.createElement("App");
                rootElement.appendChild(app);

                // set attribute to staff element
                Attr attr = doc.createAttribute("id");
                attr.setValue(DateUtil.getDateTimeToString());
                app.setAttributeNode(attr);

                // shorten way
                // staff.setAttribute("id", "1");

                // firstname elements
                Element window = doc.createElement("window");
                window.appendChild(doc.createTextNode(application.getWindow()));
                app.appendChild(window);

                // lastname elements
                Element user = doc.createElement("user");
                user.appendChild(doc.createTextNode(application.getUser()));
                app.appendChild(user);

                // nickname elements
                Element start = doc.createElement("start");
                start.appendChild(doc.createTextNode(application.getStart()));
                app.appendChild(start);

                // salary elements
                Element end = doc.createElement("end");
                end.appendChild(doc.createTextNode(application.getEnd()));
                app.appendChild(end);

                // type elements
                Element type = doc.createElement("type");
                type.appendChild(doc.createTextNode(application.getType()));
                app.appendChild(type);

                // write the content into xml filePath
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(filePath));

                // Output to console for testing
                // StreamResult result = new StreamResult(System.out);

                transformer.transform(source, result);
                
                System.out.println("File saved!");
                
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void createXml(String file, List<Application> list) {
        
        
        
        try {

//            Date d1 = new Date();
//            SimpleDateFormat simpDate = new SimpleDateFormat("yyyyMMddHHmmss");
//            String id = simpDate.format(d1);

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("Computer");
            doc.appendChild(rootElement);
            
            
            
            for (Application application : list) {


                // staff elements
                Element app = doc.createElement("App");
                rootElement.appendChild(app);

                // set attribute to staff element
                Attr attr = doc.createAttribute("id");
                attr.setValue(application.getId());
                app.setAttributeNode(attr);

                // shorten way
                // staff.setAttribute("id", "1");

                // firstname elements
                Element window = doc.createElement("window");
                window.appendChild(doc.createTextNode(application.getWindow()));
                app.appendChild(window);

                // lastname elements
                Element user = doc.createElement("user");
                user.appendChild(doc.createTextNode(application.getUser()));
                app.appendChild(user);

                // nickname elements
                Element start = doc.createElement("start");
                start.appendChild(doc.createTextNode(application.getStart()));
                app.appendChild(start);

                // salary elements
                Element end = doc.createElement("end");
                end.appendChild(doc.createTextNode(application.getEnd()));
                app.appendChild(end);

                // type elements
                Element type = doc.createElement("type");
                type.appendChild(doc.createTextNode(application.getType()));
                app.appendChild(type);
            }



            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(file));

            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

            transformer.transform(source, result);
            
            System.out.println("File saved!");
            
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }
    
    public static void removeXml(String file, String id) {
        List<Application> list = readFileXml(file);
        
        if (list.size() > 0) {
            for (Application application : list) {
                if (application.getId().equals(id)) {
                    list.remove(application);
                    break;
                    
                }
            }
        }
        
        
        System.out.println(list.size());
        
        createXml(file,list);
    }
    
    public static void editXml(String file, Application application) {
        try {
            String filepath = file;
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);

            // Get the root element
            Node computer = doc.getFirstChild();
            // Get the staff element , it may not working if tag has spaces, or
            // whatever weird characters in front...it's better to use
            // getElementsByTagName() to get it directly.
            // Node staff = company.getFirstChild();
            // Get the staff element by tag name directly
            NodeList appList = doc.getElementsByTagName("App");
            
            for (int temp = 0; temp < appList.getLength(); temp++) {
                
                Node app = appList.item(temp);
                
                NamedNodeMap attr = app.getAttributes();
                String id = attr.getNamedItem("id").getTextContent();
                
                
                if (id.equals(application.getId())) {
//                    System.out.println(id);

                    NodeList appChildNodes = app.getChildNodes();
                    
                    for (int i = 0; i < appChildNodes.getLength(); i++) {
                        
                        Node node = appChildNodes.item(i);

                        // get the salary element, and update the value
                        if ("window".equals(node.getNodeName())) {
                            node.setTextContent(application.getWindow());
                        }
                        
                        
                        if ("user".equals(node.getNodeName())) {
                            node.setTextContent(application.getUser());
                        }
                        
                        if ("start".equals(node.getNodeName())) {
                            node.setTextContent(application.getStart());
                        }
                        
                        if ("end".equals(node.getNodeName())) {
                            node.setTextContent(application.getEnd());
                        }
                        
                        if ("type".equals(node.getNodeName())) {
                            node.setTextContent(application.getType());
                        }
                        
                    }
                    
                    break;
                    
                }
                
            }





            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);
            
            System.out.println("Done");
            
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SAXException sae) {
            sae.printStackTrace();
        }
    }
}
